package edu.zju.gis.dbfg.fileserver.controller;

import com.google.gson.*;
import edu.zju.gis.dbfg.common.Page;
import edu.zju.gis.dbfg.common.Result;
import edu.zju.gis.dbfg.common.base.BaseController;
import edu.zju.gis.dbfg.common.util.DateUtils;
import edu.zju.gis.dbfg.common.util.FileUtil;
import edu.zju.gis.dbfg.fileserver.config.BackendFileSystemConfiguration;
import edu.zju.gis.dbfg.fileserver.config.CommonSetting;
import edu.zju.gis.dbfg.fileserver.constant.ConstructedDataFieldType;
import edu.zju.gis.dbfg.fileserver.constant.ConstructedDataType;
import edu.zju.gis.dbfg.fileserver.model.*;
import edu.zju.gis.dbfg.fileserver.model.search.ConstructedDatasetSearch;
import edu.zju.gis.dbfg.fileserver.model.vo.CreateDataSetRequest;
import edu.zju.gis.dbfg.fileserver.model.vo.FieldsMap;
import edu.zju.gis.dbfg.fileserver.model.vo.PublishMapServerRequest;
import edu.zju.gis.dbfg.fileserver.service.ConstructedDatasetService;
import edu.zju.gis.dbfg.fileserver.service.LoaderMonitorService;
import edu.zju.gis.dbfg.fileserver.service.RoleService;
import edu.zju.gis.dbfg.fileserver.util.*;
import edu.zju.gis.dbfg.fileserver.util.reader.ShpFileReader;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.io.File;
import java.nio.file.Path;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.*;

@CrossOrigin
@Controller
@RequestMapping("/dataset")
public class DataSpatialController extends BaseController<ConstructedDataset, ConstructedDatasetService, String, ConstructedDatasetSearch> {
    public static String tag = "";
    @Autowired
    private BackendFileSystemConfiguration fileSetting;
    @Autowired
    private CommonSetting settings;
    @Autowired
    private RoleService roleService;
    @Autowired
    private LoaderMonitorService loaderMonitorService;
    private PreparedStatement stmt;
    private Connection connection;

    @RequestMapping(value = "/all", method = RequestMethod.GET)
    @ResponseBody
    public Result getDatasets(@SessionAttribute("userId") String userId, Page page) {
        Page<ConstructedDataset> datasets = this.service.selectByPage(userId, page);
        return Result.success().setBody(datasets);
    }

    //获取个人数据集
    @RequestMapping(value = "/allFinish", method = RequestMethod.GET)
    @ResponseBody
    public Result getDatasetsFinish(@SessionAttribute("userId") String userId, Page page) {
        Page<ConstructedDataset> datasets = this.service.selectByPageFinish(userId, page);
        return Result.success().setBody(datasets);
    }

    @RequestMapping(value = "/allFinishPublic", method = RequestMethod.GET)
    @ResponseBody
    public Result getDatasetsPublicFinish(@SessionAttribute("userId") String userId, Page page) {
        Page<ConstructedDataset> datasets = this.service.selectAllPublicFinish(userId, page);
        return Result.success().setBody(datasets);
    }

    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    @ResponseBody
    public Result getDatasets(@PathVariable String id) {
        ConstructedDataset dataset = this.service.select(id);
        if (dataset != null)
            return Result.success().setBody(dataset);
        else
            return Result.error().setMessage("无法获得对应数据集。");
    }

    @RequestMapping(value = "/{id}/delete", method = RequestMethod.DELETE)
    @ResponseBody
    public Result deleteDatasets(@PathVariable String id) {
        ConstructedDataset dataset = this.service.select(id);
        if (dataset != null) {
            dataset.setStoretype("NONE");
            int count = this.service.update(dataset);
            if (count > 0)
                return Result.success().setMessage("数据集删除成功");
            else
                return Result.error().setMessage("数据集删除失败");
        } else
            return Result.error().setMessage("无法获得对应数据集。");
    }

    @RequestMapping(value = "/init", method = RequestMethod.GET)
    @ResponseBody
    public Result getFieldsInfo(@SessionAttribute("userId") String userId, String path, String hasHead) {
        String mypath = getUserPath(userId, path);
        try {
            ConstructedDataset temp = LocalFileIOUtil.getDatasetFromFile(mypath, Boolean.valueOf(hasHead));
            //猜数据的datatype
            String dataType = "POLYGON";
            List<String> lines = LocalFileIOUtil.getStrByLine(mypath, 2);
            for (String line : lines) {
                if (line.contains("MULTIPOLYGON") || line.contains("POLYGON")) {
                    dataType = "POLYGON";
                } else if (line.contains("POLYLINE")) {
                    dataType = "POLYLINE";
                } else if (line.contains("POINT")) {
                    dataType = "POINT";
                } else {
                    dataType = "TABLE";
                }
            }
            temp.setDatatype(dataType);
            return Result.success().setBody(temp);
        } catch (Exception e) {
            return Result.error("获取数据字段信息失败。");
        }
    }

    @RequestMapping(value = "/create", method = RequestMethod.POST)
    @ResponseBody
    public Result createNewSpatialServer(@SessionAttribute("userId") String userId, @RequestBody CreateDataSetRequest requestBody) {
        String path0 = requestBody.getPath();
        String path = getUserPath(userId, path0);
        Boolean hasHead = requestBody.getHasHead();
        ConstructedDataset constructedData = requestBody.getConstructedData();
        List<FieldsMap> fieldsMap = requestBody.getFieldsMap();
        constructedData.setUserid(userId);
        try {
            File myfile = new File(path);
            Path currectPath = myfile.toPath();
            //todo 将constructedData中isGeomertry的部分改name为GEOM,fieldsmap中同理
            JsonParser parser = new JsonParser();
            JsonArray fieldsArray = parser.parse(constructedData.getFields()).getAsJsonArray();
            Gson gson = new Gson();
            ArrayList<ConstructedDataField> metaFields = new ArrayList<>();

            for (JsonElement field : fieldsArray) {
                ConstructedDataField ConstructedDataField = gson.fromJson(field, ConstructedDataField.class);
                if (ConstructedDataField.getIsGeometry()) {
                    tag = ConstructedDataField.getName();
                    ConstructedDataField.setName("shape");
                    ConstructedDataField.setText("shape");
                }
                metaFields.add(ConstructedDataField);
            }

            constructedData.setFields(gson.toJson(metaFields));
            for (int i = 0; i < fieldsMap.size(); i++) {
                String sourceName = fieldsMap.get(i).getSource();
                if (sourceName.equals(tag)) {
                    FieldsMap map = new FieldsMap();
                    map.setSource("shape");
                    map.setTarget("shape");
                    fieldsMap.set(i, map);
                }
            }

            boolean isImported = LocalFileIOUtil.ImportFromLocal(currectPath.toString(), hasHead, constructedData, fieldsMap);
            if (isImported) {
                this.service.insert(constructedData);
                return Result.success().setMessage("数据入库");
            } else
                return Result.error("入库失败,字段规范不正确。");
        } catch (Exception e) {
            System.out.println(e.getMessage());
            return Result.error("入库失败:");
        }
    }

    //使用师兄的分布式模型
    @RequestMapping(value = "/create2", method = RequestMethod.POST)
    @ResponseBody
    public Result createNewSpatialServer2(@SessionAttribute("userId") String userId, @RequestBody CreateDataSetRequest2 requestBody) {
        System.out.println("！！！！进入函数！！！！！");
        String cors = requestBody.getConstructedData().getCors();
        String path0 = requestBody.getPath();
        String datasetName = path0.substring(path0.lastIndexOf("/") + 1, path0.length() - 4);
        String path = getUserPath(userId, path0);

        //向数据库插入数据
//        sql = "insert into tb_constructed_data VALUES('" + this.uuid + "','" + this.arg.getUserId() + "','" + type + "',-1,'" + this.dataset.getDescription() + "','" + this.dataset.getPicurl() + "','" + jsonArray.toString() + "','" + df.format(new Date()) + "','" + df.format(new Date()) + " ',1,'polygon','ES',999,'" + rs.getString(1) + "')";
//
//        String sql2 = "insert into tb_loader_monitor VALUES('" + this.uuid + "','" + type + "','" + df.format(new Date()) + "',0,0,'Loading',' ','" + this.arg.getUserId() + "')";


        ConstructedDataset2 output = requestBody.getConstructedData();
        String paramStr = "";
        if (path0.contains("csv")) {
//            JSONArray fields = outPutFormat.getJSONArray("fields");
            ArrayList<ConstructedDataField2> formatedFields = output.getFields();
//        把geometry字段命名为GEOM，配合模型使用
            for (ConstructedDataField2 constructedDataField2 : formatedFields) {
                if (constructedDataField2.getIsGeometry()) {
                    constructedDataField2.setName("GEOM");
                    constructedDataField2.setText("GEOM");
                }
            }
//            }
            ConstructedDataset2 dataset = new ConstructedDataset2(formatedFields);
            JSONArray jsonArray = new JSONArray();
            for (ConstructedDataField2 constructedDataField : dataset.getFields()) {
                JSONObject jsonObject = new JSONObject(constructedDataField);
                jsonArray.put(jsonObject);
            }
            dataset.setName(datasetName);
            dataset.setUserid(userId);
            dataset.setDatatype(output.getDatatype());
            dataset.setCors(output.getCors());
//            dataset.setCreatetime(output.getCreatetime());
            if (!dataset.getDatatype().equals("Table"))
                dataset.setIsspatialdata(true);
//            dataset.setSource(path);
//            Gson g = new Gson();

            Role role = roleService.departmentsAndLevel(userId);
            try {
                ConstructedDataset cons = new ConstructedDataset();
                cons.setName(datasetName);
                cons.setUserid(userId);
                cons.setId(dataset.getId());
                cons.setCreatetime(output.getCreatetime());
                cons.setLastmodifytime(output.getLastmodifytime());
                cons.setDatatype(dataset.getDatatype());
                cons.setDescription(dataset.getDescription());
                cons.setDepartments(role.getDepart());
                cons.setLevel(999);
                cons.setIsspatialdata(dataset.getIsspatialdata());
                cons.setFields(jsonArray.toString());
                int result1 = this.service.insert(cons);
                System.out.println("第一次插入数据" + result1);
                LoaderMonitor loaderMonitor = new LoaderMonitor();
                loaderMonitor.setDatasetname(dataset.getName());
                loaderMonitor.setUserId(userId);
                loaderMonitor.setId(dataset.getId());
                loaderMonitor.setCreatetime(output.getCreatetime());
                int result2 = loaderMonitorService.save(loaderMonitor);
                System.out.println("第2次插入数据" + result2);
            } catch (Exception e) {
                System.out.println(e);
//                throws e;
            }
            System.out.println("向数据库插入数据");

            Gson g = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();
            paramStr = " -userId " + userId + " -crs " + cors + " -input " + "file://" + path + " -output " + dataset.getId() + "/" + dataset.getName() + " -meta " +
                    '"' + g.toJson(dataset).replace("\"", "\\\"") + '"';
        }
        String driverMemory = "1g";
        String numExecutors = "3";
        String executorMemory = "1g";
        String executorCores = "1";
        String jarPath = settings.getImportToolJarPath();
        String cmd = settings.getSparkHome() +
                "/bin/spark-submit" +
                " --class " + settings.getImportToolJarClass() +
                " --master yarn --deploy-mode cluster --driver-memory " + driverMemory +
                " --num-executors " + numExecutors +
                " --executor-memory " + executorMemory +
                " --executor-cores " + executorCores +
                " --name " + datasetName + " " +
                jarPath + " " + paramStr;
        System.out.println("!!!!!输出cmd的值");
        System.out.println(cmd);
        try {
            SSHHelper.runSSH(settings.getNameNode(), settings.getUsername(), settings.getPassword(), cmd, settings.getParallelFilePath());
//                log.info("A new export task is submitted with cmd: [" + cmd + "].");
//            this.service.
            return Result.success().setMessage("数据入库");
        } catch (Exception e) {
//                log.info("Cmd: [" + cmd + "] was failed to submit.");
            return Result.error("入库失败:");
        }
//            boolean isImported = LocalFileIOUtil.ImportFromLocal(currectPath.toString(), hasHead, constructedData, fieldsMap);
//            if (isImported) {
//                this.service.insert(constructedData);
//                return Result.success().setMessage("数据入库");
//            } else
//                return Result.error("入库失败,字段规范不正确。");
//        } catch (Exception e) {
//            System.out.println(e.getMessage());
//            return Result.error("入库失败:");
//        }
//        }catch(Exception e) {
//            System.out.println(e.getMessage());
//            return Result.error("入库失败:");
//        }
    }


    //读取shp文件中的字段信息，构建construteddataset
    @RequestMapping(value = "/init/shp", method = RequestMethod.GET)
    @ResponseBody
    public Result getFieldsInfoFromShp(@SessionAttribute("userId") String userId, String path) {
        String userPath = getUserPath(userId, path);
        try {
            ShpFileReader reader = new ShpFileReader();
            reader.filename(userPath);
            reader.init();
            FieldInfo[] headers = reader.getHeaderInfo();
            String shpType = reader.getShpType();
            reader.close();
            List<ConstructedDataField> fields = new ArrayList<>();
            for (FieldInfo header : headers) {
                ConstructedDataField field = new ConstructedDataField(header.getName());
                field.setType(header.getType());
                field.setLength(header.getLength());
                if (field.getType().equals(ConstructedDataFieldType.Date.name())) {
                    field.setIsTime(true);
                    field.setFormat("EEE MMM dd HH:mm:ss zzz yyyy");
                }
                fields.add(field);
            }
            ConstructedDataset temp = new ConstructedDataset(fields);
            int startIndex = path.lastIndexOf(File.separator) + 1;
            int endIndex = path.lastIndexOf(".");
            temp.setName(path.substring(startIndex, endIndex));
            temp.setIsspatialdata(true);
            temp.setDescription("数据描述...");
            temp.setDatatype(switchTypeName(shpType).name());
            return Result.success().setBody(temp);
        } catch (Exception e) {
            return Result.error("获取数据字段信息失败。");
        }
    }

    //shp文件入库
    @RequestMapping(value = "/create/shp", method = RequestMethod.POST)
    @ResponseBody
    public Result createNewSpat(@SessionAttribute("userId") String userId, @RequestBody CreateDataSetRequest requestBody) {
        String userPath = getUserPath(userId, requestBody.getPath());
//        String userPath = "/Users/moral/Desktop/DBFG" + requestBody.getPath();

        ConstructedDataset dataset = requestBody.getConstructedData();
        List<FieldsMap> fieldsMap = requestBody.getFieldsMap();
        dataset.setUserid(userId);
        FieldsMap geoMap = new FieldsMap();
        geoMap.setSource("shape");
        geoMap.setTarget("shape");
        fieldsMap.add(geoMap);

        ArrayList<ConstructedDataField> metaFields = new ArrayList<>();
        JsonParser parser = new JsonParser();
        Gson gson = new Gson();
        JsonArray fieldsArray = parser.parse(dataset.getFields()).getAsJsonArray();
        for (JsonElement field : fieldsArray) {
            ConstructedDataField ConstructedDataField = gson.fromJson(field, ConstructedDataField.class);
            metaFields.add(ConstructedDataField);
        }
        ConstructedDataField shapeField = new ConstructedDataField();
        shapeField.setName("shape");
        shapeField.setText("shape");
        shapeField.setFormat("wkt");
        shapeField.setIsGeometry(true);
        metaFields.add(shapeField);
        dataset.setFields(gson.toJson(metaFields));
        Role role = this.roleService.departmentsAndLevel(userId);
        dataset.setDepartments(role.getDepart());
        dataset.setLevel(999);

        LoaderMonitor loaderMonitor=new LoaderMonitor();
        loaderMonitor.setId(dataset.getId());
        loaderMonitor.setDatasetname(dataset.getName());
        loaderMonitor.setCreatetime(DateUtil.now());
        loaderMonitor.setErrornumb(0);
        loaderMonitor.setSuccessnumb(0);
        loaderMonitor.setStatus("Init");
        loaderMonitor.setLogs("Start");
        loaderMonitor.setUserId(dataset.getUserid());
        loaderMonitorService.save(loaderMonitor);

        boolean isImported = LocalFileIOUtil.ImportFromShp(userPath, dataset, fieldsMap,loaderMonitor);

        if (isImported) {
            this.service.insert(dataset);
            return Result.success().setMessage("数据入库");
        } else
            return Result.error("入库失败,字段规范不正确。");
    }

    private String getUserPath(String id, String path) {
        return fileSetting.getSelfDataNameSpace() + id + path;
    }

    private ConstructedDataType switchTypeName(String shpType) {
        if (shpType.contains("Point") || shpType.contains("MultiPoint"))
            return ConstructedDataType.Point;
        if (shpType.contains("LineString") || shpType.contains("MultiLineString"))
            return ConstructedDataType.LineString;
        if (shpType.contains("Polygon") || shpType.contains("MultiPolygon"))
            return ConstructedDataType.Polygon;
        return ConstructedDataType.Table;
    }

    @RequestMapping(value = "/init/tiff", method = RequestMethod.POST)
    @ResponseBody
    public Result PublishTiff(@SessionAttribute("userId") String userId, @RequestBody PublishMapServerRequest requestBody) {
        String id = UUID.randomUUID().toString();
        Role role = roleService.departmentsAndLevel(userId);
        String sql = "insert into tb_service values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
        String updateSql = "update tb_service set status = ? where id = ?";
        try {
            connection = JdbcUtil.getConnection();
            stmt = connection.prepareStatement(sql);
            stmt.setString(1, "admin");
            stmt.setString(2, id);
            stmt.setString(3, requestBody.getLayerName());
            stmt.setString(4, "http://121.89.211.142:9600/dbfg/gttileservice/" + id + "/geotrellis/{z}/{x}/{y}/");
            stmt.setString(5, requestBody.getKeywords());
            stmt.setString(6, "TMS");
            stmt.setString(7, requestBody.getTopic());
            stmt.setString(8, "WGS84");
            stmt.setString(9, "经纬度");
            stmt.setString(10, "");
            stmt.setTimestamp(11, Timestamp.valueOf(DateUtils.curDateTimeStrDefault()));
            stmt.setString(12, "");
            stmt.setString(13, "***/topography.png");
            stmt.setString(14, userId);
            stmt.setString(15, "");
            stmt.setString(16, "raster");
            stmt.setString(17, getUserPath(userId, requestBody.getInput()));
            stmt.setString(18, "loading");
            stmt.setString(19, role.getDepart());
            stmt.setString(20, "999");
            stmt.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }

        String paramStr = "-address http://121.89.211.142:9600/dbfg/gttileservice/ -layerName "
                + requestBody.getLayerName() + " -tiffPath //" + getUserPath(userId, requestBody.getInput())
                + " -keywords " + requestBody.getKeywords() + " -bandsSelected " + requestBody.getBands()
                + " -topic " + requestBody.getTopic() + " -userId " + userId + " -serviceId " + id;
        String driverMemory = "1g";
        String numExecutors = "2";
        String executorMemory = "1g";
        String executorCores = "1";
        String jarPath = settings.getImportTiffJarPath();
        String cmd = settings.getSparkHome() +
                "/bin/spark-submit" +
                " --class " + settings.getImportTiffJarClass() +
                " --master yarn --deploy-mode cluster --driver-memory " + driverMemory +
                " --num-executors " + numExecutors +
                " --executor-memory " + executorMemory +
                " --executor-cores " + executorCores +
                " --name " + requestBody.getLayerName() + " " +
                jarPath + " " + paramStr;
        System.out.println("!!!!!输出cmd的值");
        System.out.println(cmd);
        try {
            SSHHelper.runSSH(settings.getNameNode(), settings.getUsername(), settings.getPassword(), cmd, settings.getParallelFilePath());
            String finalStatus = getStatus(requestBody.getLayerName());
            if(finalStatus.equals("SUCCEEDED")) {
                try {
                    stmt = connection.prepareStatement(updateSql);
                    stmt.setString(1, "succeeded");
                    stmt.setString(2, id);
                    stmt.executeUpdate();
                } catch (SQLException sqlE) {
                    sqlE.printStackTrace();
                } finally {
                    if (stmt != null) {
                        try {
                            stmt.close();
                        } catch (SQLException e) {
                            e.printStackTrace();
                        }
                    }
                    if (connection != null) {
                        try {
                            connection.close();
                        } catch (SQLException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }else if(finalStatus.equals("FAILED")) {
                try {
                    stmt = connection.prepareStatement(updateSql);
                    stmt.setString(1, "failed");
                    stmt.setString(2, id);
                    stmt.executeUpdate();
                } catch (SQLException sqlE) {
                    sqlE.printStackTrace();
                }finally {
                    if (stmt != null) {
                        try {
                            stmt.close();
                        } catch (SQLException e) {
                            e.printStackTrace();
                        }
                    }
                    if (connection != null) {
                        try {
                            connection.close();
                        } catch (SQLException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
            return Result.success().setMessage("瓦片服务");
        } catch (Exception e) {
            try {
                stmt = connection.prepareStatement(updateSql);
                stmt.setString(1, "failed");
                stmt.setString(2, id);
                stmt.executeUpdate();
            } catch (SQLException sqlE) {
                e.printStackTrace();
            }
            return Result.error("发布失败");
        }
    }

    @RequestMapping(value = "/init/es", method = RequestMethod.POST)
    @ResponseBody
    public Result PublishEs(@SessionAttribute("userId") String userId, @RequestBody PublishMapServerRequest requestBody) {
        Role role = roleService.departmentsAndLevel(userId);
        String id = UUID.randomUUID().toString();
        String sql = "insert into tb_service values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
        String updateSql = "update tb_service set status = ? where id = ?";
        try {
            connection = JdbcUtil.getConnection();
            stmt = connection.prepareStatement(sql);
            stmt.setString(1, "admin");
            stmt.setString(2, id);
            stmt.setString(3, requestBody.getLayerName());
            stmt.setString(4, "http://121.89.211.142:9600/dbfg/gttileservice/" + id + "/geotrellis/{z}/{x}/{y}/");
            stmt.setString(5, requestBody.getKeywords());
            stmt.setString(6, "TMS");
            stmt.setString(7, requestBody.getTopic());
            stmt.setString(8, "WGS84");
            stmt.setString(9, "经纬度");
            stmt.setString(10, "");
            stmt.setTimestamp(11, Timestamp.valueOf(DateUtils.curDateTimeStrDefault()));
            stmt.setString(12, "");
            stmt.setString(13, "***/topography.png");
            stmt.setString(14, userId);
            stmt.setString(15, "");
            stmt.setString(16, "raster");
            stmt.setString(17, "ES:" + requestBody.getInput());
            stmt.setString(18, "loading");
            stmt.setString(19, role.getDepart());
            stmt.setString(20, "999");
            stmt.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }

        String paramStr = "-address http://121.89.211.142:9600/shengting/gttileservice/ -layerName "
                + requestBody.getLayerName() + " -indexName " + requestBody.getInput()
                + " -keywords " + requestBody.getKeywords() + " -fieldsInfo " + requestBody.getFields()
                + " -topic " + requestBody.getTopic() + " -userId " + userId + " -serviceId " + id;
        String driverMemory = "1g";
        String numExecutors = "2";
        String executorMemory = "1g";
        String executorCores = "1";
        String jarPath = settings.getImportESJarPath();
        String cmd = settings.getSparkHome() +
                "/bin/spark-submit" +
                " --class " + settings.getImportESJarClass() +
                " --master yarn --deploy-mode cluster --driver-memory " + driverMemory +
                " --num-executors " + numExecutors +
                " --executor-memory " + executorMemory +
                " --executor-cores " + executorCores +
                " --name " + requestBody.getLayerName() + " " +
                jarPath + " " + paramStr;
        System.out.println("!!!!!输出cmd的值");
        System.out.println(cmd);

        try {
            SSHHelper.runSSH(settings.getNameNode(), settings.getUsername(), settings.getPassword(), cmd, settings.getParallelFilePath());
            String finalStatus = getStatus(requestBody.getLayerName());
            if(finalStatus.equals("SUCCEEDED")) {
                try {
                    stmt = connection.prepareStatement(updateSql);
                    stmt.setString(1, "succeeded");
                    stmt.setString(2, id);
                    stmt.executeUpdate();
                } catch (SQLException sqlE) {
                    sqlE.printStackTrace();
                } finally {
                    if (stmt != null) {
                        try {
                            stmt.close();
                        } catch (SQLException e) {
                            e.printStackTrace();
                        }
                    }
                    if (connection != null) {
                        try {
                            connection.close();
                        } catch (SQLException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }else if(finalStatus.equals("FAILED")) {
                try {
                    stmt = connection.prepareStatement(updateSql);
                    stmt.setString(1, "failed");
                    stmt.setString(2, id);
                    stmt.executeUpdate();
                } catch (SQLException sqlE) {
                    sqlE.printStackTrace();
                }finally {
                    if (stmt != null) {
                        try {
                            stmt.close();
                        } catch (SQLException e) {
                            e.printStackTrace();
                        }
                    }
                    if (connection != null) {
                        try {
                            connection.close();
                        } catch (SQLException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
            return Result.success().setMessage("数据上图");
        } catch (Exception e) {
            try {
                stmt = connection.prepareStatement(updateSql);
                stmt.setString(1, "failed");
                stmt.setString(2, id);
                stmt.executeUpdate();
            } catch (SQLException sqlE) {
                sqlE.printStackTrace();
            }finally {
                if (stmt != null) {
                    try {
                        stmt.close();
                    } catch (SQLException sqlE) {
                        e.printStackTrace();
                    }
                }
                if (connection != null) {
                    try {
                        connection.close();
                    } catch (SQLException sqlE) {
                        e.printStackTrace();
                    }
                }
            }
            return Result.error("发布失败");
        }
    }

    private String getStatus(String jobName) throws Exception {
        String finalStatus = null;
        String monitorResult;
        while (true) {
            monitorResult = HttpRequestUtil.get("http://121.89.211.142:13000/ws/v1/cluster/apps", null, "utf-8");
            JSONObject apps = new JSONObject(monitorResult);
            JSONArray infos = apps.getJSONObject("apps").getJSONArray("app");
            int i = infos.length() - 1;
            for (; i >= 0; i--) {
                if (infos.getJSONObject(i).getString("name").equals(jobName)) {
                    finalStatus = infos.getJSONObject(i).getString("finalStatus");
                    if(finalStatus.equals("FAILED") || finalStatus.equals("SUCCEEDED")) {
                        return finalStatus;
                    }
                }
            }
            Thread.sleep(1000 * 5);
        }
    }

}